import { QuestDefaultApi } from '@/library/util/api';
import { filterNonNullable } from '@/library/util/array';
import { defaultErrorHandler } from '@/library/util/error-handler';
import { PaginationParam } from '@/model/common/PaginationParam';
import QuestionaireBasic from '@/model/questionaire/QuestionaireBasic';
import { defineStore } from 'pinia';
import { useManageRespositoryStore } from '.';
import { useLoginInforStore } from '../login';
interface ManageQueryState {
  /** 请求参数 */
  // queryParams: any;

  /** 分页参数 */
  pagination: PaginationParam;

  /** 加载状态 */
  isLoading: boolean;

  /** 当前查询结果(ids) */
  resultIds: string[];
}
export const useManageQueryStore = defineStore({
  id: 'ManageQueryStore',
  state: (): ManageQueryState => ({
    isLoading: false,
    pagination: new PaginationParam(),
    resultIds: [],
  }),
  getters: {
    result(): QuestionaireBasic[] {
      const repo = useManageRespositoryStore();

      const result = this.resultIds
        .map((id) => repo.questionnaires.get(id))
        .filter(filterNonNullable);
      return result;
    },
  },
  actions: {
    /**
     * 请求全部问卷
     * @returns
     */
    async query() {
      try {
        const useLoginStore = useLoginInforStore();

        if (!useLoginStore.userInfo.userId) {
          throw new Error('用户id为空请刷新重试');
        }

        const params = {
          userId: useLoginStore.userInfo.userId,
          pageNum: this.pagination.pageNum.toString(),
          pageSize: this.pagination.pageSize.toString(),
        };

        this.isLoading = true;

        const result = await QuestDefaultApi.questionaireQuestionaireListGet(
          params,
        );

        if (!(result && result.questionaires)) return;

        // 保存
        const repo = useManageRespositoryStore();
        result.questionaires.forEach((item: QuestionaireBasic) => {
          repo.questionnaires.set(item.queId, item);
        });

        // 保存列表
        this.resultIds = result.questionaires.map(
          (item: QuestionaireBasic) => item.queId,
        );

        this.pagination.total = result.total;
      } catch (error) {
        defaultErrorHandler(error);
      } finally {
        this.isLoading = false;
      }
    },

    async queryAll() {
      try {
        const useLoginStore = useLoginInforStore();

        if (!useLoginStore.userInfo.userId) {
          throw new Error('用户id为空请刷新重试');
        }

        this.isLoading = true;
        const params1 = {
          userId: useLoginStore.userInfo.userId,
          pageNum: this.pagination.pageNum.toString(),
          pageSize: this.pagination.pageSize.toString(),
        };

        const result1 = await QuestDefaultApi.questionaireQuestionaireListGet(
          params1,
        );

        const params = {
          userId: useLoginStore.userInfo.userId,
          pageNum: '1',
          pageSize: result1.total,
        };

        const result = await QuestDefaultApi.questionaireQuestionaireListGet(
          params,
        );

        if (!(result && result.questionaires)) return;

        // 保存
        const repo = useManageRespositoryStore();
        result.questionaires.forEach((item: QuestionaireBasic) => {
          repo.questionnaires.set(item.queId, item);
        });

        // 保存列表
        this.resultIds = result.questionaires.map(
          (item: QuestionaireBasic) => item.queId,
        );

        this.pagination.total = result.total;
      } catch (error) {
        defaultErrorHandler(error);
      } finally {
        this.isLoading = false;
      }
    },

    /**
     * 删除问卷
     * @param queId
     */
    async delete(queId: string) {
      try {
        // await
        this.resultIds = this.resultIds.filter((_queId) => _queId !== queId);
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    setPage(value: number, size: number) {
      this.pagination.pageNum = value;
      this.pagination.pageSize = size;
    },
  },
});
